<?php
class AlbumAction extends Action{
    
    /**
     * 为相册上传一张图片
     */
    public function uploadAlbum(){    	
        global $userSession,$param;
        $params = $param->getParams();
        $userInfo = $userSession->getUserSession($params['sessionId']);

        tsLoad('/manage/busi/SysAlbumBusi.class.php');
        tsLoad('/manage/busi/SysPhotoBusi.class.php');
        //设置上传目录,目前废除掉了，现在是用户就以用户的登录名为图片目录，以便查询效率的提升
        //$folder = $_POST['folder']!=null?$_POST['folder'].'/':"";
        $fileElementName = 'files';
        //echo $_FILES[$fileElementName]["size"].'***************';
        if (!empty($_FILES)) {
        	//得到上传的临时文件流
        	$tempFile = $_FILES[$fileElementName]['tmp_name'];
        	
        	//允许的文件后缀
        	$fileTypes = array('jpg','jpeg','gif','png'); 
        	
        	//得到文件原名
        	$fileName = iconv("UTF-8","GB2312",$_FILES[$fileElementName]["name"]);
        	$fileParts = pathinfo($_FILES[$fileElementName]['name']);
        	
        	//接受动态传值
        	$imageSize = $_FILES[$fileElementName]["size"];
        	
        	if($imageSize < 1024*512){
        		//取得文件后缀
        		$tempArr = explode(".", $_FILES[$fileElementName]['name']);
        		$fileExt = array_pop($tempArr);
        		$fileExt = trim($fileExt);
        		$fileExt = strtolower($fileExt);
        		
        		/**
        		 * 图片路径目前会分为2种情况 
        		 * 1.用户上传的图片，以用户相册ID作为分类，如果没有给予相册ID就用0传入默认的相册里,目录以用户的登录ID作为目录名称
        		 * 2.官方上传的图片，以官方相册ID作为分类，官方的必须给予相册ID不然不予上传，由于官方图片居多相册会以年月日来分文件夹
        		 * 3.上传的所有图片应附上图片类型用途，不然服务器端也不予处理上传该图片
        		 */
        		$url = ""; //文件完整路径
        		$urlSingleFile = "";//不带扩展名的完整路径
        		$guid = guid();//图片地址
        		
        		//首先我们来判断一下属于官方的还是用户的图片,目前不是官方的就是用户的
        		if(isset($params['photoIsOffic']) && $params['photoIsOffic']==1){
        			//图片存放路径相册基准
        			$albumUrl = "";
        			if(isset($params['albumId'])){
        				$albumId = $params['albumId'];
        				if($albumId!=0){
        					$sysAlbumBusi = new SysAlbumBusi();
        					$sysAlbum = $sysAlbumBusi->queryAlbumByAlbumId($params['albumId']);
        					$albumUrl = $sysAlbum['albumTitle']."/";
        				}
        				
        				//官方的图片上传以年月日为目录以减少每个文件夹的数量降低读取时间
        				$date = date("Y/m/d")."/";
        				
        				$url = "/images/"."o/".$albumUrl.$date.$guid.'.'.$fileExt;
        				$urlSingleFile = "/images/"."o/".$albumUrl.$date.$guid;
        				
        				//相册目录
        				$albumFolder = "/images/"."o/".$albumUrl.$date;
        				//查看目录是否存在，不存在则创建
        				if(!is_readable($_SERVER["DOCUMENT_ROOT"].$albumFolder))
        				{
        					makeDir(iconv('utf-8', 'gbk', $albumFolder));
        				}
        			}else{
        				$this->assign('state','FAIL');
        				$this->assign('failReason','官方上传图片文件夹ID不能为空！！');
        				return $this->JSON;
        			}
        		}else{
        			//不是官方图片不需要进行设置，默认自动设置为0
        			$params['photoIsOffic']=0;
        			//图片存放路径相册基准
        			$albumUrl = "";
        			if(isset($params['albumId'])){
        				$albumId = $params['albumId'];
        				if($albumId!=0){
        					$sysAlbumBusi = new SysAlbumBusi();
        					$sysAlbum = $sysAlbumBusi->queryAlbumByAlbumId($params['albumId']);
        					$albumUrl = $sysAlbum['albumTitle']."/";
        				}else
        					$albumUrl = "默认相册/";
        			}else 
        				$albumUrl = "默认相册/";
        			
        			//根据用户名创建文件夹
        			$userLoginId = $userInfo['userLoginId']."/";
        			$url = "/images/"."u/".$userLoginId.$albumUrl. $guid .'.'.$fileExt;
        			$urlSingleFile = "/images/"."u/".$userLoginId.$albumUrl. $guid;
        			 
        			//相册目录
        			$albumFolder = "/images/"."u/".$userLoginId.$albumUrl;
        			//查看目录是否存在，不存在则创建
        			if(!is_readable($_SERVER["DOCUMENT_ROOT"].$albumFolder))
        			{
        				makeDir(iconv('utf-8', 'gbk', $albumFolder));
        			}
        		}
        		
        		/**
        		 * 根据类型计算需要的参数
        		 * $urlSingleFile 文件部分的地址
        		 * $fileExt 文件扩展名
        		 * $url 文件完整路径
        		 */
        		if (move_uploaded_file(stripslashes($tempFile), $_SERVER["DOCUMENT_ROOT"] . iconv('utf-8', 'gbk', $url))){
        		    //$_POST['photoSort'] = 'product';
        		    //根据图片所属归类
        		    if(isset($params['photoType'])){
        		        switch ($params['photoType']){
        		        	//内部头像图片
        		            case 4:
        		                $this->resizeImageExcute( 100, 100, $urlSingleFile, $fileExt);
        		                break;
        		            default:
        		                break;
        		        }
        		    }
        		    //echo $_SERVER["DOCUMENT_ROOT"] . iconv('utf-8', 'gbk', $url);
        			//读取文件宽和高
        			$arr=getimagesize($_SERVER["DOCUMENT_ROOT"] . iconv('utf-8', 'gbk', $url));
        			$strarr=explode("\"",$arr[3]);
        			$width = $strarr[1];
        			$height = $strarr[3];
        			//$msg .= " File Name: " . $_FILES[$fileElementName]['name'] . ", ";
        			//$msg .= " File Size: " . $_FILES[$fileElementName]['size'] . ", ";
        			//$msg .= " File Width: " . $width . ", ";
        			//$msg .= " File Height: " . $height . " ";
        			$sysPhotoBusi = new SysPhotoBusi();
        			$result = $sysPhotoBusi->uploadPhoto(
        			        array(
        			               "photoName" => $_FILES[$fileElementName]['name'], 
        			               "photoAlbumId" => $albumId,
        			               "photoUrl" => $url,
        			               "photoWidth" => $width,
        			                "photoHeight" => $height,
        			                "photoSize" => $_FILES[$fileElementName]['size'],
        			                "photoTitle" => empty($params['pictitle'])?'暂无标题':$params['pictitle'],
        			        		"photoNoExtUrl" => $urlSingleFile,
        			        		"userId" => $userInfo['userId'],
        			        		"photoIsOffic" => $params['photoIsOffic'],
        			        		"photoType" => $params['photoType'],
        			        		"photoExt" => $fileExt
        			             )
        			);
        			$this->assign('photoName',$_FILES[$fileElementName]['name']);
        			$this->assign('photoAlbumId',$albumId);
        			$this->assign('photoUrl',$url);
        			$this->assign('photoWidth',$width);
        			$this->assign('photoHeight',$height);
        			$this->assign('photoTitle',empty($params['pictitle'])?'暂无标题':$params['pictitle']);
        			$this->assign('url',$url);
        			$this->assign('success',true);
        			$this->assign('state','SUCCESS');
        			$this->assign('fileName',$fileName);
        			$this->assign('photoId',$result);
        			$this->assign('photoNoExtUrl',$urlSingleFile);
        			$this->assign('fileExt',$fileExt);
        		}else{
        			$this->assign('state','FAIL');
        		    $this->assign('failReason','网络发展异常上传失败！');
        		}
        	}else{
        		$this->assign('state','FAIL');
        	    $this->assign('failReason','图片大小超过了512KB！');
        	}
        }else{
        	$this->assign('state','FAIL');
        	$this->assign('failReason','上传的文件不存在！');
        }
    
        return $this->JSON;
    }
    
    //执行图片缩放
    public function resizeImageExcute($maxwidth, $maxheight, $urlSingleFile, $fileExt){
        //根据缩放要求复制一个相同的图片再进行缩放
        $newImageUrl = $_SERVER["DOCUMENT_ROOT"] . iconv('utf-8', 'gbk', $urlSingleFile.'_'.$maxwidth.'x'.$maxheight.'.'.$fileExt);
        $newImageUrlNoExt = $_SERVER["DOCUMENT_ROOT"] . iconv('utf-8', 'gbk', $urlSingleFile.'_'.$maxwidth.'x'.$maxheight);
        copy($_SERVER["DOCUMENT_ROOT"] . iconv('utf-8', 'gbk', $urlSingleFile.'.'.$fileExt),$newImageUrl);

        //根据不类型进行图片生成'jpg','jpeg','gif','png'
        /* switch ($fileExt){
            case 'png':
                $img = ImageCreateFrompng($_SERVER["DOCUMENT_ROOT"] . iconv('utf-8', 'gbk', $urlSingleFile.'.'.$fileExt));
                break;
            case 'jpg':
                $img = ImageCreateFromjpeg($_SERVER["DOCUMENT_ROOT"] . iconv('utf-8', 'gbk', $urlSingleFile.'.'.$fileExt));
                break;
            case 'jpeg':
                $img = ImageCreateFromjpeg($_SERVER["DOCUMENT_ROOT"] . iconv('utf-8', 'gbk', $urlSingleFile.'.'.$fileExt));
                break;
            case 'gif':
                $img = ImageCreateFromgif($_SERVER["DOCUMENT_ROOT"] . iconv('utf-8', 'gbk', $urlSingleFile.'.'.$fileExt));
                break;
            default:
                break;
        }
        //2.上色
        $color=imagecolorallocate($img,255,255,255);
        //3.设置透明
        imagecolortransparent($img,$color);
        imagefill($img,0,0,$color); */
        $this->resizeImage($newImageUrl, $maxwidth, $maxheight, $newImageUrlNoExt, '.'.$fileExt);
        
        
        
        /* Free resources associated to the Imagick object */
        //$im->destroy();
    	// 按比例生成缩略图,不足部分用#FF0000填充 
        /* $logfile = $_SERVER["DOCUMENT_ROOT"].'/PicThumb.log';
		$param = array(
		  'type' => 'fit', 
		  'width' => 100, 
		  'height' => 100, 
		  'quality' => 50,
		  'bgcolor' => '#FFFF00'
		); 
		tsLoad('/core/CoreLib/PicThumb.class.php');
		$obj = new PicThumb($logfile); 
		$obj->set_config($param); 
		$flag = $obj->create_thumb($_SERVER["DOCUMENT_ROOT"] . iconv('utf-8', 'gbk', $urlSingleFile.'.'.$fileExt), $newImageUrl); 
		  
		if($flag){ 
		  echo '<img src="pic/'.basename($newImageUrl).'">'; 
		}else{ 
		  echo 'create thumb fail'; 
		}  */
    }
    
    //等比例缩放图片
    public function resizeImage ($imSrc, $maxwidth, $maxheight, $name, $filetype)
    {
    	/* Create the Imagick object */
    	$im = new Imagick();
    	/* Read the image file */
    	$im->readImage($imSrc);
    	
        $pic_width = $im->getimagewidth();
        $pic_height = $im->getimageheight();
        $resizewidth_tag = false;
        $resizeheight_tag = false;
        if (($maxwidth && $pic_width > $maxwidth) ||
        ($maxheight && $pic_height > $maxheight)) {
            if ($maxwidth && $pic_width > $maxwidth) {
                $widthratio = $maxwidth / $pic_width;
                $resizewidth_tag = true;
            }
    
            if ($maxheight && $pic_height > $maxheight) {
                $heightratio = $maxheight / $pic_height;
                $resizeheight_tag = true;
            }
    
            if ($resizewidth_tag && $resizeheight_tag) {
                if ($widthratio < $heightratio)
                    $ratio = $widthratio;
                else
                    $ratio = $heightratio;
            }
    
            if ($resizewidth_tag && ! $resizeheight_tag)
                $ratio = $widthratio;
            if ($resizeheight_tag && ! $resizewidth_tag)
                $ratio = $heightratio;
    
            $newwidth = $pic_width * $ratio;
            $newheight = $pic_height * $ratio;
            
            /* Thumbnail the image ( width 100, preserve dimensions ) */
            $im->thumbnailImage( $newwidth, $newheight );
             
            /* Write the thumbail to disk */
            $im->writeImage($imSrc);
        }
    }
    
    public function calculatePhoto($width,$height,$frameWidth,$frameHeight){
        $sizeArray = array();
        //如果不需要缩小
        if($width<=$frameWidth && $height<=$frameHeight){
            $sizeArray[0] = $width;
            $sizeArray[1] = $height;
        }
        //如果需要缩小
        else{
            //按长的一边的比例进行缩小
            //如果宽比高长,宽就变成边框宽
            //alert('photo.photoWidth:'+photo.photoWidth+'\n'+'photo.photoHeight:'+photo.photoHeight+'\n');
            if($width>$height){
                $sizeArray[0] = $frameWidth;
                $sizeArray[1] = $frameWidth/$width*$height;
                
                //width:frameWidth,
                //height:frameWidth/photo.photoWidth*photo.photoHeight,
                //marginTop:Math.floor((frameHeight-frameWidth/photo.photoWidth*photo.photoHeight)/2)
                
            }else if($width<$height){
                $sizeArray[0] = $frameHeight/$height*$width;
                $sizeArray[1] = $frameHeight;
                //height:frameHeight,
                //width:frameHeight/photo.photoHeight*photo.photoWidth,
                //marginLeft:Math.floor((frameWidth-frameHeight/photo.photoHeight*photo.photoWidth)/2)
                
            }else{
                $sizeArray[0] = $frameWidth;
                $sizeArray[1] = $frameHeight;
            }
        }
        
        return $sizeArray;
    }
    
    /**
     * 通过图片ID删除图片
     * @return string
     */
    public function delPhotoByPhotoId(){
        global $userSession,$param;
        $params = $param->getParams();
        $userInfo = $userSession->getUserSession();
    	
        tsLoad('/manage/busi/SysPhotoBusi.class.php');
        $sysPhotoBusi = new SysPhotoBusi();
    
        if(isset($userInfo['userInfo'])){
            $result = $sysPhotoBusi->delPhotoByPhotoId($params['photoId']);
            $this->assign('result',$result);
        }else {
            $this->assign('error','请登录后使用相册！');
        }
    
        return $this->JSON;
    }
    
    /**
     * 通过相册ID寻找相册图片
     * @return string
     */
    public function queryPhotosByAlbumId(){
    	global $userSession,$param;
    	$params = $param->getParams();
    	$userInfo = $userSession->getUserSession();
    	
        tsLoad('/manage/busi/SysPhotoBusi.class.php');
        $sysPhotoBusi = new SysPhotoBusi();
    
        if(isset($userInfo['userInfo'])){
            $photos = $sysPhotoBusi->queryPhotosByAlbumId($params);
            $this->assign('photos',$photos);
        }else {
            $this->assign('error','请登录后使用相册！');
        }
    
        return $this->JSON;
    }
    
    /**
     * 查看用户相册
     * @return string
     */
    public function queryAlbumByUserId(){
        session_start();
        tsLoad('/manage/busi/SysAlbumBusi.class.php');
        $sysAlbumBusi = new SysAlbumBusi();
        if(isset($_SESSION['userInfo'])){
            $albums = $sysAlbumBusi->queryAlbumByUserId($_SESSION['userInfo']['userId']);
            $this->assign('albums',$albums);
        }else {
            $this->assign('error','请登录后使用相册！');
        }
    
        return $this->JSON;
    }
    
    /**
     * 增加一个相册
     * @return string
     */
    public function addAlbum(){
        tsLoad('/manage/busi/SysAlbumBusi.class.php');
        $sysAlbumBusi = new SysAlbumBusi();
        $result = $sysAlbumBusi->addAlbum($_POST);
        
        if(!$result){
            $this->assign('result',0);
            $this->assign('msg',$result);
        }
        else{
            $this->assign('result',1);
            $this->assign('albumId',$result);
        }
        
        return $this->JSON;
    }
    
    /**
     * 删除一个相册
     */
    public function delAlbum(){
        tsLoad('/manage/busi/SysAlbumBusi.class.php');
        $sysAlbumBusi = new SysAlbumBusi();
        $result = $sysAlbumBusi->delAlbum($_POST);
        
        if(!$result){
            $this->assign('result',0);
            $this->assign('msg',$result);
        }
        else{
            $this->assign('result',1);
        }
        
        return $this->JSON;
    }
    
    /**
     * 
     * @return string
     */
    public function testUeditor(){
        //mkdir('D:\workspacePhp\yufei\images\userAlbum\新相册', 0777);
        
    }
    
    /**
     * 相册管理
     * @return string
     */
    public function albumManage(){
        //查询相册的内容需要所属用户ID进行权限过滤开启session
        session_start();
        tsLoad('/manage/busi/SysPhotoPage.class.php');
        $sysPhotoPage = new SysPhotoPage();
        $pageInfo = $sysPhotoPage->initPage($_GET, 35, 1);
        $photosData = $sysPhotoPage->getCurPageData();
        $this->assign('albumId',$_GET["albumId"]);
        $this->assign('photosJson',json_encode($photosData));
        $this->assign('pageInfoJson',json_encode($pageInfo));
    }
    
    /**
     * 相册管理分页请求json请求
     * @return string
     */
    public function albumPage(){
        //查询相册的内容需要所属用户ID进行权限过滤开启session
        session_start();
        tsLoad('/manage/busi/SysPhotoPage.class.php');
        $sysPhotoPage = new SysPhotoPage();
        $pageInfo = $sysPhotoPage->initPage($_POST, 35, $_POST['currentPage']);
        $photosData = $sysPhotoPage->getCurPageData();
        $this->assign('photosData',$photosData);
        $this->assign('pageInfo',$pageInfo);
        
        return $this->JSON;
    }
    
    /**
     * 测试上传插件
     */
    public function testUpload(){
    }
}
?>